<template>
    <div>
        <div class="main-table">
            <div class="table" v-for="item in tableList" :key="item.id">
                <img :src="getImage(IMG_MAP[item.status])" alt="" @click="show(item)">
                <p class="fz16">桌号:{{ item.id }}</p>
                <p class="fz16">状态: {{ STATUS_MAP[item.status] }}</p>
                <p> {{ useTime(item) }}</p>
            </div>
        </div>
        <!-- 弹出对话框 -->
        <el-dialog v-model="dialogVisible" :title="`桌号:${clickId}`" width="70%" :before-close="handleClose">
            <el-row :gutter="15">
                <el-col :span="8">
                    <span style="line-height: 40px;">请选择操作</span>
                </el-col>
                <el-col :span="16">
                    <el-select v-model="value" placeholder="Select" size="large">
                        <el-option v-for="item in options" :key="item.value" :label="item.label" :value="item.value" />
                    </el-select>
                </el-col>
            </el-row>
            <el-row style="margin-top: 20px; line-height: 40px;" :gutter="15" v-if="value === 2">
                <el-col :span="8">
                    <span>预约时间</span>
                </el-col>
                <el-col :span="16">
                    <el-time-select v-model="timeValue" start="08:00" step="00:30" end="21:00" placeholder="Select time"
                        :min-time="minTime()" />
                </el-col>
            </el-row>
            <template #footer>
                <div class="dialog-footer">
                    <el-button @click="dialogVisible = false">取消</el-button>
                    <el-button type="primary" @click="submit()">
                        确定
                    </el-button>
                </div>
            </template>
        </el-dialog>
        <!-- 预约码对话框 -->
        <el-dialog v-model="reservationShow" title="预约码" width="500">
            <p>预约码： {{ reservationCode }}</p>
            <p>超过预约时间30分钟将自动将预约取消</p>
            <el-button type="success" @click="reservationShow = false">确定</el-button>
        </el-dialog>
    </div>
</template>

<script setup>
import { getImage } from '@/utils';
import { ElMessage } from 'element-plus';
import { onMounted, onUnmounted, ref } from 'vue';
import { getTableList, chooseTable } from '@/api/dashed.js'
import { useRouter } from 'vue-router';
import useUserStore from '@/stores/module/user';
const userStore = useUserStore()
const router = useRouter()
const STATUS_MAP = ['空闲', '使用中', '预约中', '维修中', '已损坏']
const IMG_MAP = ['table-ini.png', 'table-play.png', 'table-active.png', 'table-maintenance.png', 'table-error.png']
//预约码管理
const reservationShow = ref(false)
const reservationCode = ref('暂无预约码')
//获取球桌数据
const tableList = ref(null)
const getList = async () => {
    console.log("我触发了吗")
    const { data } = await getTableList()
    tableList.value = data
}
onMounted(async () => {
    await getList()
    userStore.getUseruseTable()
})

//点击空闲球桌的逻辑
const clickId = ref(null)
const dialogVisible = ref(false)
const options = ref([
    {
        value: 1,
        label: '立即开始',
    },
    {
        value: 2,
        label: '预约时间',
    }
])
/**
 * @description: 预约时间不能低于当前的时间
 * @return {*}
 */
const minTime = () => {
    const time = new Date()
    let hour = time.getHours()
    let min = time.getMinutes()
    if (min <= 30 && min !== '00') {
        min = 30
    } else {
        hour = hour + 1
        min = '00'
    }
    return `${hour}:${min}`
}
const value = ref(1)
let timeValue = ref(minTime())
const handleClose = () => {
    dialogVisible.value = false
    value.value = 1
    timeValue.value = minTime()
    clickId.value = ''
}
/**
 * @description: 对话框提交的逻辑
 * @return {*}
 */
const submit = async () => {
    const res = await chooseTable({
        id: clickId.value,
        status: value.value,
        startTime: value.value === 1 ? Date.now().toString() : timeValue.value,
        userAccount: userStore.account
    })
    if (res.code === 2000) {
        if (value.value === 2) {
            ElMessage({
                type: 'success',
                message: "预约成功"
            })
            reservationCode.value = res.data.randomCode
            reservationShow.value = true
            console.log(res)
            handleClose()
        } else {
            ElMessage({
                type: 'success',
                message: "选桌成功"
            })
            router.push({ path: `/table/${clickId.value}`, query: { status: 1 } })
        }
        getList()
    } else {
        ElMessage({
            type: 'error',
            message: "选桌失败，请联系管理员"
        })
    }
    handleClose()
}
/**
 * @description: 根据球桌状态和时间返回对应的时间文本
 * @param {*} status  本桌状态
 * @param {*} startTime  本桌起始时间
 * @return {*}
 */
const useTime = (item) => {
    if (item.status === 1) {
        const nowdate = Date.now() - item.startTime
        const hours = Math.floor(nowdate / (1000 * 60 * 60));
        const minutes = Math.floor((nowdate % (1000 * 60 * 60)) / (1000 * 60));
        return `已使用 ${hours} 小时 ${minutes} 分钟`
    }
    if (item.status === 2) {
        const nowDate = new Date()
        const localYear = nowDate.getFullYear();
        const localMonth = String(nowDate.getMonth() + 1).padStart(2, '0');
        const localDay = String(nowDate.getDate()).padStart(2, '0');
        const localHour = nowDate.getHours()
        const localMin = nowDate.getMinutes()
        const nowTime = Number(`${localHour}${localMin}`)
        const resTime = String(item.reservationTime).replace(':', "")
        if (nowTime - resTime > 1) {
            iniTable(item)
        } else {
            return `此桌次预约时间为 ${localYear} 年 ${localMonth} 月 ${localDay}日 ${item.reservationTime}`
        }
    }

}
onMounted(() => startTime())
onUnmounted(() => {
    clearInterval(whileTime)
})
const whileTime = ref(null)
const startTime = () => {
    whileTime.value = setInterval(() => {
        tableList.value = [...tableList.value]
    }, 60000);
}
/**
 * @description: 根据球桌的状态展示不同的信息
 * @param {*} status
 * @return {*}
 */
const show = (table) => {
    if (!userStore.name) {
        ElMessage({
            type: "error",
            message: "当前未登录，请登录后使用"
        })
        return false
    }
    if (table.status === 0) {
        dialogVisible.value = true
        clickId.value = table.id
    }
    if (table.status === 1) {
        if (userStore.userUseTable.includes(table.id)) {
            router.push({ path: `/table/${table.id}`, query: { status: 1 } })
        } else {
            ElMessage({
                type: 'success',
                message: "这球桌有人玩了"
            })
        }

    }
    if (table.status === 2) {
        router.push({ path: `/table/${table.id}`, query: { status: 2 } })
    }
    if (table.status === 3) {
        ElMessage({
            type: 'warning',
            message: "当前球桌已损坏，请选择其他球桌"
        })
    }
    if (table.status === 4) {
        if (userStore.account === 'Wcadmin1') {
            ElMessage({
                type: 'error',
                message: "当前球桌已损坏，请选择其他球桌"
            })
        }
    }
}

const iniTable = async (item) => {
    await chooseTable({
        id: item.id,
        status: 0,
        startTime: null
    })
    getList()
}

</script>

<style lang="scss" scoped>
.fz16 {
    font-size: 16px;
}

.main-table {
    display: flex;
    flex-wrap: wrap;
    justify-content: flex-start;
    padding-top: 40px;
    padding-left: 60px;

    .table {
        width: 364px;
        height: 200px;
        text-align: center;

        img {
            width: 100px;
            height: 80px;

        }
    }
}
</style>
